<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function brand_sales_add_page($id) {
    return drupal_get_form('brand_sales_edit_form',$id);
}
function brand_sales_add_more_page() {
    return drupal_get_form('brand_sales_add_more_form');
}
function brand_sales_edit_page($id) {
    return drupal_get_form('brand_sales_edit_form', $id);
}

function brand_sales_edit_form($form, &$form_state) {
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
//    print_r($form_state);die;
    if (!empty($id)) {
        $record = nonghua_data_load('brand_sales', 'brand_sales_id', $id);
        if (empty($record)) {
            drupal_set_message(t('品牌销售数据不存在！'), 'status', FALSE);
            return $form;
//            drupal_goto('brand_sales/list');
        }

        $form_state['id'] = $id;
    }
    // 判断用户角色
    if(!nonghua_user_access('brand_sales', 'view', $id, !empty($record) ? $record->author_uid:0, 0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }

    if (empty($record)) {
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 3, FALSE, '','省,市,县必填');
        _insert_date_selection_form($form,$form_state,5,'',null,false);
        _insert_brand_selection_form($form,'');
    } else {
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 3, FALSE, $record->addr_id,'省,市,县必填');
        _insert_date_selection_form($form,$form_state,5,$record->year,null,false);
        _insert_brand_selection_form($form,$record->brand_id);
    }

    $form['sales'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
//        '#size' => 32,
//        '#maxlength' => 8,
        '#required' => TRUE,
        '#default_value' => !empty($record) ? $record->sales:'',
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => arg(1) == 'edit' ? '修改' : '添加',
        '#access' => nonghua_user_access('brand_sales', 'edit', $id, !empty($record) ? $record->author_uid:0, 0) ,
    );
    return $form;
}

function brand_sales_edit_form_validate($form, &$form_state) {
    $empty = false;
    $empty = !_address_element_validate($form_state);

    if(empty($form_state['values']['year'])){
        form_set_error('year', '必须填写 年份');
        $empty = true;
    }
    if(empty($form_state['values']['brand'])){
        form_set_error('brand', '必须填写 主流品牌');
        $empty = true;
    }
    if(!empty($form_state['values']['sales'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['sales']) || (strlen(explode('.',$form_state['values']['sales'])[0])>8)) {
            form_set_error('sales', "销售量格式错误");
        }
    }
    if(!$empty && arg(1) === "add"){
        $address =  _get_address_id_from_autocomplete_select($form_state);
        $query = db_select('brand_sales', 's');
        $query->condition('s.addr_id',$address);
        $query->condition('s.year',$form_state['values']['year']);
        $query->condition('s.brand_id',$form_state['values']['brand']);
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if(!empty($record)){
            form_set_error('',"该地区".$form_state['values']['year']."年"."该化肥信息已存在" );
        }
    }
    if(!$empty && arg(1) === "edit") {
        $address =  _get_address_id_from_autocomplete_select($form_state);

        $query = db_select('brand_sales', 's');
        $query->condition('s.addr_id', $address);
        $query->condition('s.year', $form_state['values']['year']);
        $query->condition('s.brand_id', $form_state['values']['brand']);
        $query->condition('s.brand_sales_id', $form_state['id'], '!=');
        $query->fields('s');
        $record = $query->execute()->fetchAssoc();
        if (!empty($record)) {
            form_set_error('', "该地区" . $form_state['values']['year'] . "年" . "该化肥信息已存在");
        }
    }

}

function brand_sales_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    if (arg(1) == 'add') { //add new brand_sales
        $nid = db_insert('brand_sales') // Table name no longer needs {}
        ->fields(array(
            'addr_id' => $address,
            'brand_id' => $form_state['values']['brand'],
            'year' => $form_state['values']['year'],
            'sales' => $form_state['values']['sales'],
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            drupal_goto('brand_sales/add/'.$nid);
        }
    } else {
        $nid = db_update('brand_sales') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'addr_id' => $address,
            'brand_id' => $form_state['values']['brand'],
            'year' => $form_state['values']['year'],
            'sales' => $form_state['values']['sales'],
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            -> condition('brand_sales_id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
    }
}


function brand_sales_add_more_form($form, &$form_state){
    $form_state['insert'] = true;
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
    $form['address'] = _insert_address_selection_form($form, $form_state,'address', 3, FALSE, '','省,市,县必填');
    _insert_date_selection_form($form,$form_state,5,'',null,false);
    $brand_options[''] = '--品牌--';
    $result = db_select('brand', 'b')
        ->fields('b', array('brand_id', 'brand_name'))
        ->execute();
    foreach ($result as $record) {
        $brand_options[$record->brand_id] = $record->brand_name;
    }
    $form['brand_1'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
//        '#default_value'=>1,
    );
    $form['sales_1'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_2'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_2'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_3'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_3'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_4'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_4'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_5'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_5'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_6'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_6'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_7'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_7'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_8'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_8'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_9'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_9'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['brand_10'] = array(
        '#type' => 'select',
//        '#title' => '品牌类型',
        '#prefix' => '<div  class="brand-search">',
        '#suffix' => '</div>',
        '#validated' => TRUE,
        '#options' => $brand_options,
    );
    $form['sales_10'] = array(
        '#type' => 'textfield',
        '#title' => '销售量（万吨）',
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' =>'添加',
    );
    return $form;
}


function brand_sales_add_more_form_validate($form, &$form_state) {
    $empty = false;
    $empty = !_address_element_validate($form_state);
    if(empty($form_state['values']['year'])){
        form_set_error('year', '必须填写 年份');
        $empty = true;
    }
//    if(empty($form_state['values']['brand'])){
//        form_set_error('brand', '必须填写 主流品牌');
//        $empty = true;
//    }
//    if(!empty($form_state['values']['sales'])){
//        $reg = '/^\d{1,8}(.\d{0,2})?$/';
//        if(!preg_match ($reg, $form_state['values']['sales']) || (strlen(explode('.',$form_state['values']['sales'])[0])>8)) {
//            form_set_error('sales', "销售量格式错误");
//        }
//    }
    for($i=1;$i<11;$i++){
        if(!$empty && isset($form_state['insert']) && $form_state['insert']){
            $address =  _get_address_id_from_autocomplete_select($form_state);
            $query = db_select('brand_sales', 's');
            $query->condition('s.addr_id',$address);
            $query->condition('s.year',$form_state['values']['year']);
            $query->condition('s.brand_id',$form_state['values']['brand_'.$i]);
            $query->fields('s');
            $record = $query->execute()->fetchAssoc();
            if(!empty($record)){
                form_set_error('',"该地区".$form_state['values']['year']."年"."该化肥信息已存在" );
            }
        }
        if(!$empty && isset($form_state['update']) && $form_state['update']) {
            $address =  _get_address_id_from_autocomplete_select($form_state);
            $query = db_select('brand_sales', 's');
            $query->condition('s.addr_id', $address);
            $query->condition('s.year', $form_state['values']['year']);
            $query->condition('s.brand_id', $form_state['values']['brand_'.$i]);
            $query->condition('s.brand_sales_id', $form_state['id'], '!=');
            $query->fields('s');
            $record = $query->execute()->fetchAssoc();
            if (!empty($record)) {
                form_set_error('', "该地区" . $form_state['values']['year'] . "年" . "该化肥信息已存在");
            }
        }
    }
}

function brand_sales_add_more_form_submit($form, &$form_state) {
    global $user;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    for($i=1;$i<11;$i++)
        if(!empty($form_state['values']['brand_'.$i]) && !empty($form_state['values']['sales_'.$i])){
            $nid = db_insert('brand_sales') // Table name no longer needs {}
            ->fields(array(
                'addr_id' => $address,
                'brand_id' => $form_state['values']['brand_'.$i],
                'year' => $form_state['values']['year'],
                'sales' => $form_state['values']['sales_'.$i],
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();
            if ($nid > 0) {
                drupal_set_message(t('添加成功！'), 'status', FALSE);
            }
        }
}


